package ObserverPattern;

import Model.Book;
import Model.User;

import java.util.ArrayList;
import java.util.List;

// 主题类，用于表示被观察的对象
class Library {
    private final List<Book> books = new ArrayList<>();
    private final List<Observer> observers = new ArrayList<>();

    // 添加图书
    public void addBook(Book book) {
        books.add(book);
    }

    // 注册观察者
    public void attach(Observer observer) {
        observers.add(observer);
    }

    // 移除观察者
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    // 通知观察者
    public void notifyObservers(Book book) {
        for (Observer observer : observers) {
            observer.update(book);
        }
    }

    // 借书操作
    public void borrowBook(User user, String title) {
        for (Book book : books) {
            if (book.getTitle().equals(title) && book.isAvailable()) {
                book.setAvailable(false);
                notifyObservers(book);
                return;
            }
        }
        System.out.println("Book " + title + " not available.");
    }
}
